package com.zxx.flowerstore.utils.common;

import com.zxx.flowerstore.entity.enums.ResultEnum;

import java.util.function.Function;

/**
 * @ClassName ThrowingFunction
 * @Author Admin
 * @Date 2021/3/20 11:48
 * @Description ThrowingFunction
 * @Version 1.0
 */
@FunctionalInterface
public interface ThrowingFunction<T, R, E extends Throwable> {
    R apply(T t) throws E;

    /**
     * 异常处理
     *
     * @param throwingFunction
     * @param <T>
     * @param <R>
     * @return
     */
    static <T, R> Function<T, R> wrapper(
            ThrowingFunction<T, R, Throwable> throwingFunction) {
        // https://blog.csdn.net/Revivedsun/article/details/79906165
        return t -> {
            try {
                return throwingFunction.apply(t);
            } catch (Throwable ex) {
                throw new MyException(ResultEnum.ERROR.getCode(), ex.getMessage());
            }
        };
    }

    /**
     * 异常处理
     *
     * @param throwingFunction
     * @param exceptionTitle
     * @param <T>
     * @param <R>
     * @return
     */
    static <T, R> Function<T, R> wrapper(
            ThrowingFunction<T, R, Throwable> throwingFunction, String exceptionTitle) {

        return t -> {
            try {
                return throwingFunction.apply(t);
            } catch (Throwable ex) {
                throw new MyException(ResultEnum.ERROR.getCode(), exceptionTitle + ex.getMessage());
            }
        };
    }
}
